<template>
  <!-- 充值卡明细 -->
  <div class="app-page">
    <el-table-form ref="form">
      <el-form-item label="统计日期:" :table-form-merge="2">
        <el-date-picker
          v-model="date1"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
        />
      </el-form-item>
      <el-button v-permission="[90302, 1]" type="primary" icon="el-icon-search" @click="search1">查询</el-button>
    </el-table-form>
    <div class="top-info">
      <div class="top-info-box">
        <el-card shadow="never">
          <img :src="image">
          <div style="line-height: 40px;">
            <p>累计新增月结客户</p>
            <div class="text">{{ infoData.totalCsmNum }}<span>人</span></div>
          </div>
        </el-card>
      </div>
      <div class="top-info-box">
        <el-card shadow="never">
          <img :src="price">
          <div style="line-height: 40px;">
            <p>累计消费金额</p>
            <div class="text">{{ infoData.receivables }}<span>元</span></div>
          </div>
        </el-card>
      </div>
      <div class="top-info-box">
        <el-card shadow="never">
          <img :src="price">
          <div style="line-height: 40px;">
            <p>累计已销单金额</p>
            <div class="text">{{ infoData.billSettledFund }}<span>元</span></div>
          </div>
        </el-card>
      </div>
      <div class="top-info-box">
        <el-card shadow="never">
          <img :src="price">
          <div style="line-height: 40px;">
            <p>累计差额减免金额</p>
            <div class="text">{{ infoData.badMoney }}<span>元</span></div>
          </div>
        </el-card>
      </div>
      <div class="top-info-box">
        <el-card shadow="never">
          <img :src="price">
          <div style="line-height: 40px;">
            <p>累计未结款金额</p>
            <div class="text">{{ infoData.totalReceivable }}<span>元</span></div>
          </div>
        </el-card>
      </div>
    </div>
    <div class="table">
      <el-table-form ref="form">
        <el-form-item class="merge-item">
          <el-select v-model="qtype" style="width: 180px; margin-right: 2px;">
            <el-option label="客户编号" value="csmCode" />
            <el-option label="客户名称" value="csmName" />
            <!-- <el-option label="充值卡号" value="cardCode" /> -->
            <el-option label="电话" value="csmRgPhone" />
          </el-select>
          <el-input v-model.trim="qtTxt" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="使用门店:">
          <el-tree-select
            v-model="orgId"
            clearable
            class="orgIdSelect"
            :popover-width="360"
            :select-params="{
              clearable: false,
              placeholder: '请选择使用门店',
              multiple:true
            }"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': true,
              props:{
                value:'orgId',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
          />
        </el-form-item>
        <el-form-item label="开通机构:">
          <el-tree-select
            v-model="query.orgSNNo"
            clearable
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: false,
              placeholder: '请选择责任机构',
            }"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': true,
              props:{
                value:'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
          />
        </el-form-item>
        <el-form-item label="开通日期:" :table-form-merge="2">
          <el-date-picker
            v-model="date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            unlink-panels
          />
        </el-form-item>
        <el-form-item label="月结状态:">
          <el-select v-model="query.settlementType" clearable>
            <el-option label="使用中" :value="2" />
            <el-option label="已停用" :value="1" />
          </el-select>
        </el-form-item>
        <template v-slot:btns>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </template>
      </el-table-form>
      <div style="margin-bottom: 10px;">
        <div>
          <el-button v-permission="[90302, 2]" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
        </div>
      </div>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        :row-class-name="seRowClass"
        @fetch="fetchData"
      />
    </div>
    <crad-info ref="cradInfo" :tree-data="treeData" :deal-map="dealMap" />
    <csm-detail
      ref="csmDetail"
      :parent-fetch-data="search"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
    />
  </div>
</template>

<script>
  import { parseTime, formatDate } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { queryMap, selectAccCsmmonthlybill, selectTotalMonthlyMoney, exportAccCsmmonthlybill, queryExportDomain, selectMonthlyBillDetailDate } from '@/api'
  import moment from 'dayjs'
  import CradInfo from './components/CradInfo.vue'
  import CsmDetail from '../../components/CsmDetailModal/index.vue'

  export default {
    name: 'refil-card-detail',
    components: {
      CradInfo,
      CsmDetail
    },
    props: {
      treeData: {
        type: Array,
        required: true
      },
      dealMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        image: require('../../../assets/person.jpg'),
        price: require('../../../assets/price.jpg'),
        infoData: {},
        query: {
          settlementType: 2,
          orgSNNo: ''
        },
        orgId: [],
        qtTxt: '',
        qtype: 'csmCode',
        date1: [],
        date: [],
        calcTypeList: [],
        paymenFilList: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      column: function() {
        return [
          {
            type: 'index',
            align: 'center'
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 150,
            render: (h, { row }) => (
              row.csmCode ? <el-link underline={false} onClick={() => this.openCsm(row)}>
                {row.csmCode}
              </el-link> : <span>{row.csmCode}</span>
            )
          },
          {
            prop: 'settlementType',
            label: '月结状态',
            width: 150,
            render: (h, { row }) => <span>{row.csmStatus !== -1 && row.settlementType && row.settlementType === 2 ? '使用中' : '已停用' }</span>
          },
          {
            prop: 'csmStatus',
            label: '客户状态',
            width: 150,
            render: (h, { row }) => {
              if (row.csmStatus === 1) {
                return <span style='font-size:14px;'>未审核</span>
              } else if (row.csmStatus === 2) {
                return <span style='font-size:14px;'>已审核</span>
              } else if (row.csmStatus === 3) {
                return <span style='font-size:14px;'>已挂失</span>
              } else if (row.csmStatus === -1) {
                return <span style='font-size:14px;color:red'>已注销</span>
              } else {
                return <span style='font-size:14px;color:red'></span>
              }
            }
          },
          {
            prop: 'csmName',
            label: '客户名称',
            width: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'csmRgPhone',
            label: '客户电话',
            width: 120
          },
          {
            prop: 'createTime',
            label: '开通时间',
            width: 180,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'decimalSpare2',
            label: '月结余额（元）',
            width: 150
            // render: (h, { row }) => <span>{row.decimalSpare2 && this.numberFormat(row.decimalSpare2, row)}</span>
          },
          {
            prop: 'decimalSpare3',
            label: '剩余余额（元）',
            width: 150
            // render: (h, { row }) => <span>{row.decimalSpare3 && this.numberFormat(row.decimalSpare3, row)}</span>
          },
          {
            prop: 'createUser',
            label: '开通人',
            width: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'orgName',
            label: '开通机构',
            width: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'useOrgName',
            label: '使用门店',
            width: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'remark',
            label: '备注',
            showOverflowTooltip: true
            // render: (h, { row }) => <span>{row.remark && this.chooseFormat(row.remark, row)}</span>
          },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            width: 100,
            render: (h, { row, $index }) => {
              return (
                <div>
                  {<el-link size='mini' underline={false} onClick={() => this.csmcardDetail(row, $index)}>月结详情</el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await this.getTimeFn()
      this.queryOptionsMap()
      this.search1()
      this.getExportDomain()
    },
    methods: {
      // 查询字典枚举
      async queryOptionsMap() {
        const [res4, res5] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' })
        ])
        this.calcTypeList = res4.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res5.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
      },
      getTimeFn() {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        this.date1[0] = formatDate(start, 'yyyy-MM-dd')
        this.date1[1] = formatDate(end, 'yyyy-MM-dd')
      },
      async fetchData({ currentPage, pageSize }) {
        const params = {
          json: {
            ...this._getQuery(this.query),
            useOrgIds: this.orgId.length > 0 ? this.orgId.join(',') : ''
          },
          pageIndex: currentPage,
          pageSize
        }
        params.json[this.qtype] = this.qtTxt
        if (this.date && this.date.length === 2) {
          params.json.createTime = moment(this.date[0]).format()
          params.json.createTimeEnd = moment(this.date[1]).format()
        } else {
          params.json.createTime = null
          params.json.createTimeEnd = null
        }
        const res = await selectAccCsmmonthlybill(params)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 打开客户
      async openCsm(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      // 月结详情
      async csmcardDetail(row) {
        const { data } = await selectMonthlyBillDetailDate({ csmId: row.csmId })
        await this.$refs.cradInfo.open(data)
      },
      async upDataCheckTable() {
        await this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 清除对象空属性
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async search1() {
        const params = {}
        if (this.date1 && this.date1.length === 2) {
          params.startDt = parseTime(this.date1[0], '{y}-{m}-{d}')
          params.endDt = parseTime(this.date1[1], '{y}-{m}-{d}')
        } else {
          params.startDt = null
          params.endDt = null
        }
        const res = await selectTotalMonthlyMoney(params)
        this.infoData = res.data
      },
      // 查询
      async search() {
        await this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 导出
      async exportFile() {
        this.$confirm('确定导出数据？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          var list = JSON.parse(JSON.stringify(this.column))
          list.pop()
          list.shift()
          const value = {}
          await list.forEach(l => {
            value[l.prop] = l.label
            return value
          })
          const params = {
            json: {
              ...this._getQuery(this.query),
              useOrgIds: this.orgId.length > 0 ? this.orgId.join(',') : ''
            }
          }
          params.json[this.qtype] = this.qtTxt
          if (this.date && this.date.length === 2) {
            params.json.createTime = moment(this.date[0]).format()
            params.json.createTimeEnd = moment(this.date[1]).format()
          } else {
            params.json.createTime = null
            params.json.createTimeEnd = null
          }
          const query = {
            paramInfo: params,
            kv: value
          }
          await exportAccCsmmonthlybill(query).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 卡余额（元）
      numberFormat(val, r) {
        var rcType = r.rcType // 为1表示余额 为2表示次数
        if (rcType === 1) {
          val = val * 1.00 / 100
        }
        val = Number(val)
        if (rcType === 1) {
          val = isNaN(val) ? '0.00' : val.toFixed(2)
          return val + ' 元'
        } else if (rcType === 2) {
          return val + ' 次'
        } else {
          return ''
        }
      },
      // 选择展示备注信息 如果是退款销卡,当前备注信息是退款销卡备注 如果是冻结卡 当前备注信息是最后一条冻结卡备注信息
      chooseFormat(val, r) {
        var cardStatus = r.cardStatus // 为1表示余额 为2表示次数
        if (cardStatus === -1 && r.refundRemark !== undefined) {
          return r.refundRemark
        } else {
          if (r.freezeRemark !== undefined) {
            return r.freezeRemark
          }
        }
      },
      // 充值金额
      numberFormat1: function(val) {
        val = val * 1.00 / 100
        val = Number(val)
        val = isNaN(val) ? '0.00' : val.toFixed(2)
        return val
      },
      seRowClass({ row, rowIndex }) {
        if (row.cardStatus === -1) return 'red-bg-row'
      }
    }
  }
</script>

<style lang="scss" scoped>
.top-info {
  display: flex;
  // justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  .top-info-box {
    width: 290px;
    height: 105px;
    padding-right: 20px;
    /deep/.el-card__body {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 105px;
    }
    img {
      width: 53px;
      height: 53px;
      background: #01999f;
      border-radius: 6px;
    }
    p {
      font-family: PingFang SC, PingFang SC-Bold;
      font-size: 16px;
      font-weight: 700;
      color: #01999f;
    }
    .text {
      display: block;
      font-family: PingFang SC, PingFang SC-Bold;
      font-size: 22px;
      font-weight: 700;
      color: #353c4e;
      text-align: right;
    }
    span {
      font-size: 14px;
    }
  }
}

</style>
